// 全局变量
let canvas;
let currentNode = null;
let isDrawingMode = false;
let nodes = [];
let connections = [];
let currentTheme = 'blue';

// 主题颜色配置
const themes = {
    blue: {
        primary: '#3b82f6',
        secondary: '#1e40af',
        accent: '#60a5fa',
        background: '#dbeafe'
    },
    green: {
        primary: '#10b981',
        secondary: '#047857',
        accent: '#34d399',
        background: '#d1fae5'
    },
    purple: {
        primary: '#8b5cf6',
        secondary: '#5b21b6',
        accent: '#a78bfa',
        background: '#ede9fe'
    }
};

// 全等三角形知识模板
const congruenceTemplate = {
    title: "全等三角形思维导图",
    nodes: [
        { id: 1, text: "全等三角形", x: 400, y: 50, color: themes.blue.primary, level: 0 },
        { id: 2, text: "定义", x: 200, y: 150, color: themes.blue.secondary, level: 1 },
        { id: 3, text: "判定方法", x: 400, y: 150, color: themes.blue.secondary, level: 1 },
        { id: 4, text: "性质", x: 600, y: 150, color: themes.blue.secondary, level: 1 },
        { id: 5, text: "应用", x: 800, y: 150, color: themes.blue.secondary, level: 1 },
        { id: 6, text: "对应边相等\n对应角相等", x: 200, y: 250, color: themes.blue.accent, level: 2 },
        { id: 7, text: "SSS", x: 300, y: 250, color: themes.blue.accent, level: 2 },
        { id: 8, text: "SAS", x: 400, y: 250, color: themes.blue.accent, level: 2 },
        { id: 9, text: "ASA", x: 500, y: 250, color: themes.blue.accent, level: 2 },
        { id: 10, text: "AAS", x: 600, y: 250, color: themes.blue.accent, level: 2 },
        { id: 11, text: "HL", x: 700, y: 250, color: themes.blue.accent, level: 2 },
        { id: 12, text: "对应边相等\n对应角相等\n周长相等\n面积相等", x: 600, y: 350, color: themes.blue.accent, level: 2 },
        { id: 13, text: "证明线段相等\n证明角相等\n计算长度\n计算角度", x: 800, y: 250, color: themes.blue.accent, level: 2 }
    ],
    connections: [
        { from: 1, to: 2 },
        { from: 1, to: 3 },
        { from: 1, to: 4 },
        { from: 1, to: 5 },
        { from: 2, to: 6 },
        { from: 3, to: 7 },
        { from: 3, to: 8 },
        { from: 3, to: 9 },
        { from: 3, to: 10 },
        { from: 3, to: 11 },
        { from: 4, to: 12 },
        { from: 5, to: 13 }
    ]
};

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeCanvas();
    setupEventListeners();
    setupPaperSize();
});

// 初始化画布
function initializeCanvas() {
    const canvasElement = document.getElementById('canvas');
    canvas = new fabric.Canvas('canvas', {
        width: 800,
        height: 600,
        backgroundColor: '#ffffff'
    });
    
    // 启用画布交互
    canvas.selection = true;
    canvas.hoverCursor = 'pointer';
    
    // 添加箭头标记
    const arrowHead = new fabric.Path('M 0 0 L -10 -5 L -10 5 z', {
        fill: '#6b7280'
    });
    canvas.add(arrowHead);
}

// 设置事件监听器
function setupEventListeners() {
    // 导出按钮
    document.getElementById('exportPNG').addEventListener('click', exportToPNG);
    document.getElementById('exportPDF').addEventListener('click', exportToPDF);
    document.getElementById('clearCanvas').addEventListener('click', clearCanvas);
    
    // 模板按钮
    document.getElementById('loadTemplate').addEventListener('click', loadCongruenceTemplate);
    
    // 主题按钮
    document.querySelectorAll('.theme-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const theme = e.currentTarget.dataset.theme;
            changeTheme(theme);
        });
    });
    
    // 节点工具
    document.getElementById('addNode').addEventListener('click', addNodeMode);
    document.getElementById('addConnection').addEventListener('click', addConnectionMode);
    
    // 纸张设置
    document.getElementById('paperSize').addEventListener('change', updatePaperSize);
    document.getElementById('paperOrientation').addEventListener('change', updatePaperSize);
    
    // 节点编辑
    document.getElementById('saveNode').addEventListener('click', saveNodeEdit);
    document.getElementById('cancelEdit').addEventListener('click', closeNodeModal);
    
    // 画布事件
    canvas.on('mouse:down', handleCanvasClick);
    canvas.on('object:moving', handleObjectMoving);
    canvas.on('object:selected', handleObjectSelected);
}

// 设置纸张尺寸
function setupPaperSize() {
    const paperSize = document.getElementById('paperSize').value;
    const orientation = document.getElementById('paperOrientation').value;
    
    let width, height;
    
    if (paperSize === 'a4') {
        width = orientation === 'landscape' ? 1123 : 794;
        height = orientation === 'landscape' ? 794 : 1123;
    } else {
        width = orientation === 'landscape' ? 1587 : 1123;
        height = orientation === 'landscape' ? 1123 : 1587;
    }
    
    canvas.setWidth(width);
    canvas.setHeight(height);
    canvas.renderAll();
}

// 更新纸张尺寸
function updatePaperSize() {
    setupPaperSize();
}

// 加载全等三角形模板
function loadCongruenceTemplate() {
    clearCanvas();
    
    const template = congruenceTemplate;
    
    // 创建节点
    template.nodes.forEach(nodeData => {
        const node = createNode(nodeData.text, nodeData.x, nodeData.y, nodeData.color);
        node.nodeId = nodeData.id;
        canvas.add(node);
    });
    
    // 创建连接线
    template.connections.forEach(conn => {
        const fromNode = canvas.getObjects().find(obj => obj.nodeId === conn.from);
        const toNode = canvas.getObjects().find(obj => obj.nodeId === conn.to);
        
        if (fromNode && toNode) {
            createConnection(fromNode, toNode);
        }
    });
    
    canvas.renderAll();
}

// 创建节点
function createNode(text, x, y, color) {
    const lines = text.split('\n');
    const maxLength = Math.max(...lines.map(line => line.length));
    const width = Math.max(120, maxLength * 12);
    const height = Math.max(40, lines.length * 20);
    
    const rect = new fabric.Rect({
        left: x,
        top: y,
        width: width,
        height: height,
        fill: color,
        stroke: '#ffffff',
        strokeWidth: 2,
        rx: 8,
        ry: 8
    });
    
    const textObj = new fabric.Text(text, {
        left: x + width / 2,
        top: y + height / 2,
        fontSize: 14,
        fill: '#ffffff',
        textAlign: 'center',
        originX: 'center',
        originY: 'center',
        fontWeight: 'bold'
    });
    
    const group = new fabric.Group([rect, textObj], {
        left: x,
        top: y,
        hasControls: true,
        hasBorders: true,
        selectable: true
    });
    
    group.on('mousedown', function() {
        currentNode = group;
    });
    
    return group;
}

// 添加节点模式
function addNodeMode() {
    canvas.defaultCursor = 'crosshair';
    canvas.on('mouse:down', function(options) {
        if (options.target) return;
        
        const pointer = canvas.getPointer(options.e);
        const color = themes[currentTheme].primary;
        const node = createNode('新节点', pointer.x - 60, pointer.y - 20, color);
        canvas.add(node);
        canvas.renderAll();
    });
}

// 添加连接线模式
function addConnectionMode() {
    let startNode = null;
    
    canvas.on('mouse:down', function(options) {
        if (!options.target) return;
        
        if (!startNode) {
            startNode = options.target;
        } else {
            createConnection(startNode, options.target);
            startNode = null;
            canvas.renderAll();
        }
    });
}

// 创建连接线
function createConnection(fromNode, toNode) {
    const fromCenter = {
        x: fromNode.left + fromNode.width / 2,
        y: fromNode.top + fromNode.height / 2
    };
    
    const toCenter = {
        x: toNode.left + toNode.width / 2,
        y: toNode.top + toNode.height / 2
    };
    
    const line = new fabric.Line([
        fromCenter.x, fromCenter.y,
        toCenter.x, toCenter.y
    ], {
        stroke: themes[currentTheme].secondary,
        strokeWidth: 2,
        selectable: false,
        evented: false
    });
    
    // 添加箭头
    const angle = Math.atan2(toCenter.y - fromCenter.y, toCenter.x - fromCenter.x);
    const arrowSize = 10;
    
    const arrow = new fabric.Triangle({
        left: toCenter.x - arrowSize * Math.cos(angle),
        top: toCenter.y - arrowSize * Math.sin(angle),
        width: arrowSize,
        height: arrowSize,
        fill: themes[currentTheme].secondary,
        angle: angle * 180 / Math.PI + 90,
        selectable: false,
        evented: false
    });
    
    canvas.add(line);
    canvas.add(arrow);
    
    // 将连接线与节点关联
    fromNode.connections = fromNode.connections || [];
    toNode.connections = toNode.connections || [];
    
    fromNode.connections.push({ line, arrow, target: toNode });
    toNode.connections.push({ line, arrow, source: fromNode });
}

// 更改主题
function changeTheme(theme) {
    currentTheme = theme;
    const themeColors = themes[theme];
    
    // 更新所有节点颜色
    canvas.getObjects().forEach(obj => {
        if (obj.type === 'group' && obj._objects && obj._objects[0].type === 'rect') {
            obj._objects[0].set('fill', themeColors.primary);
        }
    });
    
    canvas.renderAll();
}

// 导出为PNG
function exportToPNG() {
    const dataURL = canvas.toDataURL({
        format: 'png',
        quality: 1.0
    });
    
    const link = document.createElement('a');
    link.download = '全等三角形思维导图.png';
    link.href = dataURL;
    link.click();
}

// 导出为PDF
function exportToPDF() {
    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF({
        orientation: canvas.width > canvas.height ? 'l' : 'p',
        unit: 'px',
        format: [canvas.width, canvas.height]
    });
    
    const dataURL = canvas.toDataURL({
        format: 'png',
        quality: 1.0
    });
    
    pdf.addImage(dataURL, 'PNG', 0, 0, canvas.width, canvas.height);
    pdf.save('全等三角形思维导图.pdf');
}

// 清空画布
function clearCanvas() {
    if (confirm('确定要清空画布吗？')) {
        canvas.clear();
        canvas.backgroundColor = '#ffffff';
        canvas.renderAll();
    }
}

// 处理画布点击
function handleCanvasClick(options) {
    if (options.target) {
        // 双击编辑节点
        if (options.e.type === 'dblclick') {
            editNode(options.target);
        }
    }
}

// 编辑节点
function editNode(node) {
    if (!node || node.type !== 'group') return;
    
    const textObj = node._objects.find(obj => obj.type === 'text');
    if (textObj) {
        document.getElementById('nodeText').value = textObj.text;
        document.getElementById('nodeColor').value = node._objects[0].fill;
        currentNode = node;
        document.getElementById('nodeModal').classList.remove('hidden');
    }
}

// 保存节点编辑
function saveNodeEdit() {
    if (!currentNode) return;
    
    const text = document.getElementById('nodeText').value;
    const color = document.getElementById('nodeColor').value;
    
    const textObj = currentNode._objects.find(obj => obj.type === 'text');
    const rectObj = currentNode._objects.find(obj => obj.type === 'rect');
    
    if (textObj && rectObj) {
        textObj.set('text', text);
        rectObj.set('fill', color);
        
        // 调整大小
        const lines = text.split('\n');
        const maxLength = Math.max(...lines.map(line => line.length));
        const width = Math.max(120, maxLength * 12);
        const height = Math.max(40, lines.length * 20);
        
        rectObj.set({ width, height });
        textObj.set({ left: width / 2, top: height / 2 });
        
        canvas.renderAll();
    }
    
    closeNodeModal();
}

// 关闭节点编辑弹窗
function closeNodeModal() {
    document.getElementById('nodeModal').classList.add('hidden');
    currentNode = null;
}

// 处理对象移动
function handleObjectMoving(options) {
    const obj = options.target;
    
    // 更新连接线
    if (obj.connections) {
        obj.connections.forEach(conn => {
            if (conn.line) {
                const fromCenter = {
                    x: obj.left + obj.width / 2,
                    y: obj.top + obj.height / 2
                };
                
                let toCenter;
                if (conn.target) {
                    toCenter = {
                        x: conn.target.left + conn.target.width / 2,
                        y: conn.target.top + conn.target.height / 2
                    };
                } else if (conn.source) {
                    toCenter = fromCenter;
                    fromCenter = {
                        x: conn.source.left + conn.source.width / 2,
                        y: conn.source.top + conn.source.height / 2
                    };
                }
                
                conn.line.set({
                    x1: fromCenter.x,
                    y1: fromCenter.y,
                    x2: toCenter.x,
                    y2: toCenter.y
                });
                
                if (conn.arrow) {
                    const angle = Math.atan2(toCenter.y - fromCenter.y, toCenter.x - fromCenter.x);
                    conn.arrow.set({
                        left: toCenter.x - 10 * Math.cos(angle),
                        top: toCenter.y - 10 * Math.sin(angle),
                        angle: angle * 180 / Math.PI + 90
                    });
                }
            }
        });
    }
}

// 处理对象选择
function handleObjectSelected(options) {
    // 可以在这里添加选中时的特殊效果
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    if (e.key === 'Delete' || e.key === 'Backspace') {
        const activeObject = canvas.getActiveObject();
        if (activeObject) {
            canvas.remove(activeObject);
            canvas.renderAll();
        }
    }
});
